// game.js: === JavaScript代码文件: game.js ===

// 游戏配置
const GAME_CONFIG = {
    basePath: '',
    characterImagesPath: ''
};

// 属性相克表 (新增 'neutral' 作为默认值，避免undefined)
const ELEMENT_CHART = {
    algorithm: { strong: ['rhetoric', 'retro'], weak: ['geography'], emoji: '💻' },
    retro: { strong: ['geography', 'mecha'], weak: ['algorithm'], emoji: '🕹️' },
    geography: { strong: ['algorithm', 'basketball'], weak: ['rhetoric'], emoji: '🌍' },
    basketball: { strong: ['mecha', 'rhetoric'], weak: ['geography'], emoji: '🏀' },
    mecha: { strong: ['algorithm', 'geography'], weak: ['basketball'], emoji: '🤖' },
    rhetoric: { strong: ['retro', 'mecha'], weak: ['basketball'], emoji: '🗣️' },
    neutral: { strong: [], weak: [], emoji: '⚪' } // 兜底
};

// 角色数据（已更新，包含新的技能和属性）
const characters = [
    {
        id: 1, name: '成成', image: '/test/photos/chengcheng.png', element: 'algorithm', elementName: '算法系',
        description: '大二偏科理工男，脑筋好使！', baseHp: 125, baseMp: 85, baseAttack: 10, baseDefense: 5, baseSpeed: 8,
        skills: [
            { id: 1, name: '代码注入', description: '向敌人系统注入恶意代码，造成基础伤害。', damage: 15, cost: 5, pp: 10, effectDuration: 0 },
            { id: 2, name: '递归算法', description: '强力算法攻击，伤害递增，仿佛无穷尽的计算。', damage: 26, cost: 9, pp: 7, effectDuration: 0 },
            { id: 3, name: '性能优化', description: '对自身系统进行优化，提升攻击力和少量速度，持续3回合。', damage: 0, cost: 7, pp: 6, buff: { attack: 8, speed: 3 }, effectDuration: 3 },
            // 成成 - 分治打击: 增加 chance 属性
            { id: 4, name: '分治打击', description: '将问题分解为子问题解决，对敌人造成巨大打击，可能造成眩晕1回合。', damage: 42, cost: 16, pp: 3, effectDuration: 1, statusEffect: 'stun', chance: 0.75 } // 75% 眩晕几率
        ]
    },
    {
        id: 2, name: '凡凡', image: '/test/photos/fanfan.png', element: 'retro', elementName: '复古系',
        description: 'I wanna玩家，热爱红白机复古游戏，双截龙是信仰！', baseHp: 155, baseMp: 75, baseAttack: 9, baseDefense: 7, baseSpeed: 6,
        skills: [
            { id: 1, name: '像素冲击', description: '释放怀旧的像素能量，造成基础伤害。', damage: 12, cost: 5, pp: 10, effectDuration: 0 },
            { id: 2, name: '地刺陷阱', description: '在敌人脚下制造I wanna式的地刺陷阱，造成伤害并大幅降低速度，持续2回合。', damage: 20, cost: 8, pp: 7, debuff: { speed: 8 }, effectDuration: 2 },
            { id: 3, name: '存档点', description: '回到最近的存档点，恢复生命值并获得少量防御提升，持续3回合。', damage: -35, cost: 10, pp: 5, buff: { defense: 8 }, effectDuration: 3 },
            { id: 4, name: '双截龙连击', description: '唤醒经典双截龙招式，对敌人进行高额连击 (2段伤害)。', damage: 20, numHits: 2, cost: 15, pp: 3, effectDuration: 0 } // 多段伤害
        ]
    },
    {
        id: 3, name: '娇娇', image: '/test/photos/jiaojiao.png', element: 'geography', elementName: '地理系',
        description: '地理张老师，温柔淑女，掌控自然之力。', baseHp: 105, baseMp: 110, baseAttack: 8, baseDefense: 6, baseSpeed: 9,
        skills: [
            { id: 1, name: '自然之语', description: '用温柔的自然之力攻击敌人，造成基础伤害。', damage: 10, cost: 4, pp: 12, effectDuration: 0 },
            { id: 2, name: '地形改造', description: '改变战场地形，造成伤害并降低敌人的防御和速度，持续2回合。', damage: 16, cost: 7, pp: 8, debuff: { defense: 8, speed: 5 }, effectDuration: 2 },
            { id: 3, name: '春风化雨', description: '如春风般滋润大地，为自身恢复大量生命值，并在2回合内持续恢复少量生命值。', damage: -25, cost: 12, pp: 4, hot: { value: 10, duration: 2 }, effectDuration: 2 }, // HoT
            { id: 4, name: '智慧之树', description: '召唤智慧之树的力量，造成中等伤害并恢复自身少量MP。', damage: 30, cost: 10, pp: 5, restoreMp: 10, effectDuration: 0 }
        ]
    },
    {
        id: 4, name: '老哥', image: '/test/photos/oldbrother.png', element: 'basketball', elementName: '篮球系',
        description: '稳重、可靠的大哥，篮球场上更是一把好手！', baseHp: 185, baseMp: 65, baseAttack: 11, baseDefense: 10, baseSpeed: 5,
        skills: [
            { id: 1, name: '乌鸦坐飞机', description: '阿福的常用招数，基础物理攻击。', damage: 14, cost: 5, pp: 10, effectDuration: 0 },
            { id: 2, name: '梦幻脚步', description: '在篮球场上灵活穿梭，造成伤害并降低对方速度，持续2回合。', damage: 18, cost: 8, pp: 7, debuff: { speed: 5 }, effectDuration: 2 },
            { id: 3, name: '铁血防守', description: '像一道坚不可摧的城墙，大幅提升自身防御力，持续3回合。', damage: 0, cost: 10, pp: 4, buff: { defense: 18 }, effectDuration: 3 },
            // 老哥 - 龙卷风摧毁停车场: 增加 chance 属性
            { id: 4, name: '龙卷风摧毁停车场', description: '老哥的招牌绝技，造成毁灭性伤害，但自身会受到反冲，并有几率沉默敌人1回合。', damage: 50, cost: 20, pp: 2, recoil: 12, statusEffect: 'silence', effectDuration: 1, chance: 0.6 } // 60% 沉默几率
        ]
    },
    {
        id: 5, name: '涛涛', image: '/test/photos/taotao.png', element: 'mecha', elementName: '机甲系',
        description: '在重庆上学并谈了女朋友的帅小伙，高基础攻击力，速度与爆发兼备！', baseHp: 95, baseMp: 95, baseAttack: 18, baseDefense: 4, baseSpeed: 10,
        skills: [
            { id: 1, name: '月牙能量波', description: '洛洛历险记中的经典招式，基础能量攻击。', damage: 13, cost: 4, pp: 12, effectDuration: 0 },
            // 涛涛 - 流影电光闪: 增加 chance 属性
            { id: 2, name: '流影电光闪', description: '化作一道闪电，对敌人进行强力电击，有几率造成眩晕1回合。', damage: 25, cost: 8, pp: 8, statusEffect: 'stun', effectDuration: 1, chance: 0.7 }, // 70% 眩晕几率
            { id: 3, name: '暴龙神之怒', description: '唤醒体内的暴龙神之力，瞬间提升攻击力并恢复少量MP，持续2回合，准备爆发！', damage: 0, cost: 0, pp: 5, buff: { attack: 12 }, restoreMp: 10, effectDuration: 2 },
            { id: 4, name: '雷霆半月斩', description: '洛洛历险记终极技能，用雷霆之力撕裂敌人，必定暴击。', damage: 45, cost: 18, pp: 3, effectDuration: 0, critical: true } // 必定暴击
        ]
    },
    {
        id: 6, name: '文鑫', image: '/test/photos/wenxin.png', element: 'rhetoric', elementName: '嘴炮系',
        description: '六人中年龄最小身高最高，以言语和精神力量操控战场，嘴皮子功夫了得！', baseHp: 115, baseMp: 125, baseAttack: 7, baseDefense: 5, baseSpeed: 7,
        skills: [
            { id: 1, name: '精神嘲讽', description: '用犀利的言语攻击敌人精神，造成少量伤害并略微降低其攻击力，持续2回合。', damage: 11, cost: 5, pp: 10, debuff: { attack: 3 }, effectDuration: 2 },
            // 文鑫 - 语言陷阱: 增加 chance 属性
            { id: 2, name: '语言陷阱', description: '布下文字陷阱，造成伤害并大幅降低敌人速度，持续2回合，并有几率沉默敌人1回合。', damage: 20, cost: 8, pp: 7, debuff: { speed: 8 }, statusEffect: 'silence', effectDuration: 1, chance: 0.65 }, // 65% 沉默几率
            { id: 3, name: '话术大师', description: '通过精妙的话术恢复大量MP，并小幅提升自身速度，持续3回合。', damage: 0, cost: 0, pp: 6, restoreMp: 20, buff: { speed: 5 }, effectDuration: 3 },
            { id: 4, name: '嘴遁奥义', description: '究极精神爆发，用语言的力量造成无法承受的打击，并降低敌人所有属性2回合。', damage: 48, cost: 18, pp: 2, debuff: { attack: 10, defense: 10, speed: 10 }, effectDuration: 2 }
        ]
    }
];

// 游戏状态
const gameState = {
    player: null,
    enemy: null,
    currentBattle: 1,
    totalBattles: 5,
    isPlayerTurn: true,
    log: [],
    playerBlockedInput: false, // 玩家输入锁定
    enemyBlockedInput: false, // 敌人行动锁定
};

// DOM 元素
const startScreen = document.getElementById('start-screen');
const characterSelection = document.getElementById('character-selection');
const battleScreen = document.getElementById('battle-screen');
const resultModal = document.getElementById('result-modal');
const pauseMenu = document.getElementById('pause-menu');

// 按钮元素
const startButton = document.getElementById('start-button');
const backToStartButton = document.getElementById('back-to-start');
const nextLevelButton = document.getElementById('next-level');
const restartGameButton = document.getElementById('restart-game');
const pauseButton = document.getElementById('pause-button');
const resumeGameButton = document.getElementById('resume-game');
const restartFromPauseButton = document.getElementById('restart-from-pause');
const returnToCharacterButton = document.getElementById('return-to-character');

// 战斗界面元素
const playerNameElement = document.getElementById('player-name');
const playerElementElement = document.getElementById('player-element');
const playerHpBarElement = document.getElementById('player-hp-bar');
const playerHpTextElement = document.getElementById('player-hp-text');
const playerMpBarElement = document.getElementById('player-mp-bar');
const playerMpTextElement = document.getElementById('player-mp-text');
const playerSpriteElement = document.getElementById('player-sprite');
const playerStatusIconsElement = document.getElementById('player-status-icons'); // 新增

const enemyNameElement = document.getElementById('enemy-name');
const enemyElementElement = document.getElementById('enemy-element');
const enemyHpBarElement = document.getElementById('enemy-hp-bar');
const enemyHpTextElement = document.getElementById('enemy-hp-text');
const enemyMpBarElement = document.getElementById('enemy-mp-bar');
const enemyMpTextElement = document.getElementById('enemy-mp-text');
const enemySpriteElement = document.getElementById('enemy-sprite');
const enemyStatusIconsElement = document.getElementById('enemy-status-icons'); // 新增

const battleStatusElement = document.getElementById('battle-status');
const battleLogElement = document.getElementById('battle-log');
const logContainer = document.getElementById('log-container'); // 获取滚动容器
const currentLevelElement = document.getElementById('current-level');
const totalLevelsElement = document.getElementById('total-levels');

// 获取角色头像的父级相对定位容器，用于眩晕特效
const playerSpriteWrapper = playerSpriteElement.parentNode;
const enemySpriteWrapper = enemySpriteElement.parentNode;

// 创建眩晕特效叠加层
function createStunOverlay(wrapper) {
    const overlay = document.createElement('div');
    overlay.className = 'stunned-overlay';
    overlay.textContent = '眩晕';
    wrapper.appendChild(overlay);
    return overlay;
}
const playerStunOverlay = createStunOverlay(playerSpriteWrapper);
const enemyStunOverlay = createStunOverlay(enemySpriteWrapper);


// ---------- 工具：可用技能数 & 兜底普攻 ----------
function hasUsableSkill(character) {
    // 检查是否有可用且未被沉默的技能 (此函数仅检查技能本身是否可用，不应受沉默影响普攻逻辑)
    if (character.isSilenced) { // 角色被沉默时，不能使用任何技能
        return false;
    }
    return character.skills.some(s => canUseSkill(character, s));
}

function canUseSkill(character, skill) {
    // 检查MP和PP
    if (character.mp < skill.cost || skill.pp <= 0) {
        return false;
    }
    // 检查是否被沉默 (此函数判断特定技能是否能使用)
    if (character.isSilenced) {
        return false;
    }
    return true;
}

// 普攻逻辑
async function performBasicAttack(attacker, defender, isPlayerSide) {
    // 动画前的短延迟，确保回合切换流畅
    await new Promise(resolve => setTimeout(resolve, 500));

    const dmg = 8 + (attacker.currentAttack / 10); // 普攻伤害也受攻击力影响
    defender.hp = Math.max(0, defender.hp - dmg);
    showDamageAnimation(isPlayerSide ? enemySpriteElement : playerSpriteElement, dmg);
    showStatusText(isPlayerSide ? enemySpriteElement : playerSpriteElement, 'hit', `-${Math.round(dmg)}`);
    gameState.log.push(`${attacker.name}使用了普通攻击，对${defender.name}造成了${Math.round(dmg)}点伤害！`);
    updateBattleUI();

    await new Promise(resolve => setTimeout(resolve, 800)); // 动画结束后再延迟一下

    if (defender.hp <= 0) {
        endBattle(isPlayerSide);
        return true;
    }
    return false;
}

// ====== 贴头像的文字特效 ======
function showStatusText(targetElement, type, text) {
    if (!targetElement || !targetElement.parentNode) return;
    const el = document.createElement('div');
    el.className = `status-fx ${type}`; // hit / heal / buff / debuff / note
    el.textContent = text;
    targetElement.parentNode.appendChild(el);
    setTimeout(() => el.remove(), 950);
}

// ====== 状态效果图标显示 ======
function displayStatusIcons(character, targetElement) {
    targetElement.innerHTML = ''; // 清空现有图标

    character.activeEffects.forEach(effect => {
        const icon = document.createElement('div');
        // 根据效果类型分配不同的CSS类，以便在output.css中自定义样式
        icon.className = `status-icon ${effect.type.includes('buff') ? 'buff' : effect.type.includes('debuff') ? 'debuff' : effect.type}`;
        let iconHtml = '';
        switch (effect.type) {
            case 'buff_attack': iconHtml = '<i class="fa fa-arrow-up"></i>'; break;
            case 'buff_defense': iconHtml = '<i class="fa fa-shield-alt"></i>'; break;
            case 'buff_speed': iconHtml = '<i class="fa fa-tachometer-alt"></i>'; break;
            case 'debuff_attack': iconHtml = '<i class="fa fa-arrow-down"></i>'; break;
            case 'debuff_defense': iconHtml = '<i class="fa fa-frown"></i>'; break;
            case 'debuff_speed': iconHtml = '<i class="fa fa-bolt"></i>'; break; // 闪电表示慢
            case 'stun': iconHtml = '<i class="fa fa-asterisk"></i>'; break; // 星号表示眩晕
            case 'silence': iconHtml = '<i class="fa fa-ban"></i>'; break; // 禁止符号表示沉默
            case 'hot': iconHtml = '<i class="fa fa-plus-circle"></i>'; break; // 持续治疗
            default: iconHtml = '?'; break;
        }
        icon.innerHTML = iconHtml;
        if (effect.duration > 0) { // 持续性效果显示回合数
            const durationSpan = document.createElement('span');
            durationSpan.className = 'duration';
            durationSpan.textContent = effect.duration;
            icon.appendChild(durationSpan);
        }
        targetElement.appendChild(icon);
    });
}

// ====== 动态计算角色当前属性 ======
function calculateCurrentStats(character) {
    // 基础属性
    let currentAttack = character.baseAttack;
    let currentDefense = character.baseDefense;
    let currentSpeed = character.baseSpeed;
    let isStunned = false;
    let isSilenced = false;

    character.activeEffects.forEach(effect => {
        if (effect.type === 'buff_attack') currentAttack += effect.value;
        if (effect.type === 'buff_defense') currentDefense += effect.value;
        if (effect.type === 'buff_speed') currentSpeed += effect.value;
        if (effect.type === 'debuff_attack') currentAttack -= effect.value;
        if (effect.type === 'debuff_defense') currentDefense -= effect.value;
        if (effect.type === 'debuff_speed') currentSpeed -= effect.value;
        if (effect.type === 'stun') isStunned = true;
        if (effect.type === 'silence') isSilenced = true;
    });

    // 确保属性不会低于某个最小值（例如0或1）
    character.currentAttack = Math.max(1, currentAttack);
    character.currentDefense = Math.max(0, currentDefense);
    character.currentSpeed = Math.max(1, currentSpeed); // 速度至少为1
    character.isStunned = isStunned;
    character.isSilenced = isSilenced;
}


// 初始化游戏
function initGame() {
    gameState.totalBattles = 5;

    startButton.addEventListener('click', goToCharacterSelection);
    backToStartButton.addEventListener('click', goToStartScreen);
    nextLevelButton.addEventListener('click', startNextBattle);
    restartGameButton.addEventListener('click', restartGame);
    pauseButton.addEventListener('click', showPauseMenu);
    resumeGameButton.addEventListener('click', hidePauseMenu);
    restartFromPauseButton.addEventListener('click', restartGame);
    returnToCharacterButton.addEventListener('click', returnToCharacterSelection);

    initCharacterSelection();
}

// 初始化角色选择界面
function initCharacterSelection() {
    const characterGrid = characterSelection.querySelector('.character-grid');
    characterGrid.innerHTML = '';

    characters.forEach(character => {
        const card = document.createElement('div');
        card.className = 'character-card';

        const imageUrl = character.image;

        card.innerHTML = `
        <div class="strip bg-${character.element}"></div>
        <div class="head">
          <h3 class="name">${character.name}</h3>
          <span class="badge bg-${character.element}">${ELEMENT_CHART[character.element]?.emoji || ''} ${character.elementName}</span>
        </div>
        <div class="avatar-wrap">
          <img src="${imageUrl}" alt="${character.name}" class="avatar" loading="lazy">
        </div>
        <p class="desc text-gray-300">${character.description}</p>
        <div class="stats-grid">
            <div class="stat-item">
                <i class="fa fa-heart text-hp"></i><span>HP: ${character.baseHp}</span>
            </div>
            <div class="stat-item">
                <i class="fa fa-bolt text-mp"></i><span>MP: ${character.baseMp}</span>
            </div>
            <div class="stat-item">
                <i class="fa fa-fist-raised text-primary"></i><span>攻击: ${character.baseAttack}</span>
            </div>
            <div class="stat-item">
                <i class="fa fa-shield-alt text-primary"></i><span>防御: ${character.baseDefense}</span>
            </div>
            <div class="stat-item">
                <i class="fa fa-running text-primary"></i><span>速度: ${character.baseSpeed}</span>
            </div>
        </div>
        <button class="select" data-character="${character.id}" title="选择${character.name}">
          选择
        </button>
      `;

        characterGrid.appendChild(card);
    });

    characterSelection.querySelectorAll('.select').forEach(button => {
        button.addEventListener('click', () => {
            const characterId = parseInt(button.getAttribute('data-character'), 10);
            selectCharacter(characterId);
        });
    });
}

// 选择角色
function selectCharacter(characterId) {
    const selectedCharacter = characters.find(c => c.id === characterId);
    if (!selectedCharacter) return;

    // 深拷贝玩家角色，并初始化临时属性和效果列表
    gameState.player = JSON.parse(JSON.stringify(selectedCharacter));
    gameState.player.maxHp = gameState.player.baseHp;
    gameState.player.maxMp = gameState.player.baseMp;
    gameState.player.hp = gameState.player.maxHp; // 初始满血
    gameState.player.mp = gameState.player.maxMp; // 初始满蓝
    gameState.player.activeEffects = []; // 清空活跃效果
    gameState.player.skills.forEach(s => {
        if (typeof s.originalPP === 'undefined') s.originalPP = s.pp;
        s.pp = s.originalPP; // 确保PP是满的
        s.used = 0;
    });

    // 随机选择敌人，确保不是玩家自己
    const pool = characters.filter(c => c.id !== characterId);
    gameState.enemy = JSON.parse(JSON.stringify(pool[Math.floor(Math.random() * pool.length)]));
    gameState.enemy.maxHp = gameState.enemy.baseHp;
    gameState.enemy.maxMp = gameState.enemy.baseMp;
    gameState.enemy.hp = gameState.enemy.maxHp;
    gameState.enemy.mp = gameState.enemy.maxMp;
    gameState.enemy.activeEffects = []; // 清空活跃效果
    gameState.enemy.skills.forEach(s => {
        if (typeof s.originalPP === 'undefined') s.originalPP = s.pp;
        s.pp = s.originalPP; // 确保PP是满的
        s.used = 0;
    });

    gameState.currentBattle = 1;
    gameState.isPlayerTurn = true;
    gameState.log = [];
    gameState.playerBlockedInput = false; // 确保初始玩家输入是解锁的
    gameState.enemyBlockedInput = false;

    // 初始计算一次属性
    calculateCurrentStats(gameState.player);
    calculateCurrentStats(gameState.enemy);

    goToBattleScreen();
}

// 更新战斗UI
function updateBattleUI() {
    if (!gameState.player || !gameState.enemy) return;

    // 重新计算当前属性（以反映 buff/debuff 变化）
    calculateCurrentStats(gameState.player);
    calculateCurrentStats(gameState.enemy);

    // 玩家信息
    playerNameElement.textContent = gameState.player.name;
    playerElementElement.textContent = `${ELEMENT_CHART[gameState.player.element]?.emoji || ''} ${gameState.player.elementName}`;
    playerElementElement.className = `px-3 py-1 rounded-full text-sm bg-${gameState.player.element}`;

    const pHP = gameState.player.hp, pMaxHP = gameState.player.maxHp;
    const pMP = gameState.player.mp, pMaxMP = gameState.player.maxMp;

    playerHpTextElement.textContent = `${pHP}/${pMaxHP}`;
    playerHpBarElement.style.width = `${Math.max(0, (pHP / pMaxHP) * 100)}%`;
    playerMpTextElement.textContent = `${pMP}/${pMaxMP}`;
    playerMpBarElement.style.width = `${Math.max(0, (pMP / pMaxMP) * 100)}%`;
    playerSpriteElement.src = gameState.player.image;
    displayStatusIcons(gameState.player, playerStatusIconsElement); // 显示玩家状态图标
    playerStunOverlay.classList.toggle('active', gameState.player.isStunned);


    // 敌人信息
    enemyNameElement.textContent = gameState.enemy.name;
    enemyElementElement.textContent = `${ELEMENT_CHART[gameState.enemy.element]?.emoji || ''} ${gameState.enemy.elementName}`;
    enemyElementElement.className = `px-3 py-1 rounded-full text-sm bg-${gameState.enemy.element}`;

    const eHP = gameState.enemy.hp, eMaxHP = gameState.enemy.maxHp;
    const eMP = gameState.enemy.mp, eMaxMP = gameState.enemy.maxMp;

    enemyHpTextElement.textContent = `${eHP}/${eMaxHP}`;
    enemyHpBarElement.style.width = `${Math.max(0, (eHP / eMaxHP) * 100)}%`;
    enemyMpTextElement.textContent = `${eMP}/${eMaxMP}`;
    enemyMpBarElement.style.width = `${Math.max(0, (eMP / eMaxMP) * 100)}%`;
    enemySpriteElement.src = gameState.enemy.image;
    displayStatusIcons(gameState.enemy, enemyStatusIconsElement); // 显示敌人状态图标
    enemyStunOverlay.classList.toggle('active', gameState.enemy.isStunned);


    // 回合提示
    if (gameState.isPlayerTurn) {
        if (gameState.player.isStunned) {
            battleStatusElement.textContent = '你被眩晕了！';
            battleStatusElement.className = 'turn-indicator'; // 眩晕状态下不显示玩家回合高亮
        } else if (gameState.player.isSilenced) {
            battleStatusElement.textContent = '你被沉默了，无法使用技能！';
            battleStatusElement.className = 'turn-indicator'; // 沉默状态下也不显示玩家回合高亮
        } else {
            battleStatusElement.textContent = '你的回合';
            battleStatusElement.className = 'turn-indicator turn-player';
        }
    } else {
        if (gameState.enemy.isStunned) {
            battleStatusElement.textContent = `${gameState.enemy.name}被眩晕了！`;
            battleStatusElement.className = 'turn-indicator'; // 眩晕状态下不显示敌人回合高亮
        } else {
            battleStatusElement.textContent = `${gameState.enemy.name}的回合`;
            battleStatusElement.className = 'turn-indicator turn-enemy';
        }
    }

    // 关卡显示
    if (currentLevelElement) currentLevelElement.textContent = gameState.currentBattle;
    if (totalLevelsElement) totalLevelsElement.textContent = gameState.totalBattles;

    updateSkillButtons();
    updateEnemySkills();
    updateBattleLog(); // 总是滚动到底部
}

// 更新技能按钮（稳定版，不重复绑定）+ 兜底普攻按钮
function updateSkillButtons() {
    const buttons = document.querySelectorAll('.skills-container .skill-button');
    let usableSkillCount = 0; // 统计可用的非普攻技能数量

    buttons.forEach((button, idx) => {
        const skill = gameState.player?.skills?.[idx];
        const nameEl = button.querySelector('[data-skill-name]');
        const ppEl = button.querySelector('[data-skill-pp]');
        const descEl = button.querySelector('[data-skill-desc]');
        const costEl = button.querySelector('[data-skill-cost]');

        if (!skill) {
            if (nameEl) nameEl.textContent = '—';
            if (ppEl) ppEl.textContent = '—';
            if (descEl) descEl.textContent = '—';
            if (costEl) costEl.textContent = '';
            button.disabled = true;
            button.onclick = null;
            return;
        }

        if (nameEl) nameEl.textContent = skill.name;
        if (ppEl) ppEl.textContent = `${skill.pp}/${skill.originalPP}`;
        if (descEl) descEl.textContent = skill.description;
        if (costEl) costEl.textContent = `消耗: ${skill.cost} MP`;


        // 技能能否使用：玩家回合，不忙碌，未被眩晕，未被沉默，MP足够，PP足够
        const canUse = gameState.isPlayerTurn &&
            !gameState.playerBlockedInput && // 检查玩家输入是否被锁定
            !gameState.player.isStunned &&
            canUseSkill(gameState.player, skill); // canUseSkill 内部会检查是否被沉默

        if (canUse) usableSkillCount++;

        button.disabled = !canUse;
        button.onclick = null;
        if (canUse) {
            button.onclick = () => useSkill(skill.id);
        }
    });

    // 无可用技能（特指非普通攻击的技能），且玩家未被眩晕，则给第1个按钮挂“普通攻击(0MP)”作为兜底
    // 关键修改：移除了对 isSilenced 的检查，因为沉默状态下应该允许普攻
    if (gameState.isPlayerTurn && !gameState.playerBlockedInput && !gameState.player.isStunned && usableSkillCount === 0 && buttons.length > 0) {
        const fallbackBtn = buttons[0];
        const nameEl = fallbackBtn.querySelector('[data-skill-name]');
        const ppEl = fallbackBtn.querySelector('[data-skill-pp]');
        const descEl = fallbackBtn.querySelector('[data-skill-desc]');
        const costEl = fallbackBtn.querySelector('[data-skill-cost]');

        if (nameEl) nameEl.textContent = '普通攻击';
        if (ppEl) ppEl.textContent = '∞';
        if (descEl) descEl.textContent = '当没有可用技能时的兜底攻击';
        if (costEl) costEl.textContent = `伤害: ${Math.round(8 + (gameState.player.currentAttack / 10))}，消耗: 0 MP`; // 动态显示普攻伤害

        fallbackBtn.disabled = false;
        fallbackBtn.onclick = async () => {
            if (!gameState.isPlayerTurn || gameState.playerBlockedInput) return;
            gameState.playerBlockedInput = true; // 锁定玩家输入

            gameState.log.push(`${gameState.player.name}别无选择，发动了普通攻击！`);
            const ended = await performBasicAttack(gameState.player, gameState.enemy, true);
            if (ended) {
                return; // 战斗结束
            }
            
            await processEndOfTurnEffects(gameState.player, true); // 玩家回合结束效果

            // 普攻结束后，切换回合，并处理状态
            gameState.isPlayerTurn = false;
            await applyStartOfTurnEffects(gameState.enemy, false); // 敌人回合开始效果
            updateBattleUI();
            setTimeout(() => enemyTurn(), 600);
        };

        // 其他技能按钮继续禁用（因为是普攻兜底模式）
        for (let i = 1; i < buttons.length; i++) {
            buttons[i].disabled = true;
            buttons[i].onclick = null;
        }
    }
}

// 敌人技能列表（信息用）
function updateEnemySkills() {
    const enemySkillsContainer = document.getElementById('enemy-skills');
    if (!enemySkillsContainer) return;
    enemySkillsContainer.innerHTML = '';

    if (gameState.enemy?.skills) {
        gameState.enemy.skills.forEach(skill => {
            const el = document.createElement('div');
            el.className = 'bg-gray-800 p-2 rounded mb-2';
            el.innerHTML = `
          <div class="flex justify-between">
            <span class="font-medium">${skill.name}</span>
            <span class="text-xs bg-gray-700 px-1 rounded">${skill.pp}/${skill.originalPP || skill.pp} PP</span>
          </div>
          <div class="text-xs text-gray-400">${skill.description} (消耗: ${skill.cost} MP)</div>
        `;
            enemySkillsContainer.appendChild(el);
        });
    }
}

// 战斗日志（强制平滑滚动到底部）
function updateBattleLog() {
    if (!logContainer) return;

    battleLogElement.innerHTML = '';
    gameState.log.forEach(entry => {
        const li = document.createElement('li');
        li.textContent = entry;
        battleLogElement.appendChild(li);
    });

    // 总是滚动到底部，确保所有DOM更新完成
    requestAnimationFrame(() => {
        logContainer.scrollTo({
            top: logContainer.scrollHeight,
            behavior: 'smooth'
        });
    });
}

// 统一处理所有状态效果的添加
function applyEffect(character, effectType, value, duration, sourceSkillName = "") {
    let logMessage = '';
    const emoji = ELEMENT_CHART[character.element]?.emoji || '';

    // 检查是否已有同类型效果（例如，攻击力buff可以叠加或刷新）
    const existingEffectIndex = character.activeEffects.findIndex(e => e.type === effectType);
    if (existingEffectIndex !== -1) {
        // 如果是数值型效果，可以叠加或刷新持续时间
        const existingEffect = character.activeEffects[existingEffectIndex];
        // 刷新持续时间，取新旧持续时间的最大值
        existingEffect.duration = Math.max(existingEffect.duration, duration);
        if (effectType.startsWith('buff_') || effectType.startsWith('debuff_')) {
            if (existingEffect.value !== value) { // 如果数值不同，更新
                existingEffect.value = value;
                logMessage = `${character.name}的${effectType.replace('buff_', '').replace('debuff_', '')}效果更新了！`;
            } else {
                logMessage = `${character.name}的${effectType.replace('buff_', '').replace('debuff_', '')}效果持续时间刷新了！`;
            }
        } else { // 非数值型效果（如晕眩、沉默），刷新持续时间即可
            logMessage = `${character.name}的${effectType}状态持续时间刷新了！`;
        }
    } else {
        // 添加新效果
        character.activeEffects.push({ type: effectType, value: value, duration: duration, sourceSkill: sourceSkillName });
        switch (effectType) {
            case 'buff_attack': logMessage = `${emoji} ${character.name}的攻击力提升了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'buff', `攻击+${value}`); break;
            case 'buff_defense': logMessage = `${emoji} ${character.name}的防御力提升了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'buff', `防御+${value}`); break;
            case 'buff_speed': logMessage = `${emoji} ${character.name}的速度提升了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'buff', `速度+${value}`); break;
            case 'debuff_attack': logMessage = `${emoji} ${character.name}的攻击力下降了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'debuff', `攻击-${value}`); break;
            case 'debuff_defense': logMessage = `${emoji} ${character.name}的防御力下降了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'debuff', `防御-${value}`); break;
            case 'debuff_speed': logMessage = `${emoji} ${character.name}的速度下降了${value}点！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'debuff', `速度-${value}`); break;
            case 'stun': logMessage = `${emoji} ${character.name}被眩晕了，无法行动！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'stun', `眩晕`); break;
            case 'silence': logMessage = `${emoji} ${character.name}被沉默了，无法使用技能！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'silence', `沉默`); break;
            case 'hot': logMessage = `${emoji} ${character.name}获得了持续治疗效果！`; showStatusText(character === gameState.player ? playerSpriteElement : enemySpriteElement, 'heal', `HoT`); break;
        }
    }
    if (logMessage) gameState.log.push(logMessage);
}

// 统一处理状态效果的移除
function removeEffect(character, effect) {
    const index = character.activeEffects.indexOf(effect);
    if (index > -1) {
        character.activeEffects.splice(index, 1);
        let logMessage = '';
        const emoji = ELEMENT_CHART[character.element]?.emoji || '';
        switch (effect.type) {
            case 'buff_attack': logMessage = `${emoji} ${character.name}的攻击力恢复正常。`; break;
            case 'buff_defense': logMessage = `${emoji} ${character.name}的防御力恢复正常。`; break;
            case 'buff_speed': logMessage = `${emoji} ${character.name}的速度恢复正常。`; break;
            case 'debuff_attack': logMessage = `${emoji} ${character.name}的攻击力恢复正常。`; break;
            case 'debuff_defense': logMessage = `${emoji} ${character.name}的防御力恢复正常。`; break;
            case 'debuff_speed': logMessage = `${emoji} ${character.name}的速度恢复正常。`; break;
            case 'stun': logMessage = `${emoji} ${character.name}从眩晕中恢复了！`; break;
            case 'silence': logMessage = `${emoji} ${character.name}从沉默中恢复了！`; break;
            case 'hot': logMessage = `${emoji} ${character.name}的持续治疗效果结束了。`; break;
        }
        if (logMessage) gameState.log.push(logMessage);
    }
}

// 新函数：处理回合开始时的效果 (HoT/DoT)
async function applyStartOfTurnEffects(character, isPlayerSide) {
    let hasEffectLog = false;
    for (let i = 0; i < character.activeEffects.length; i++) {
        const effect = character.activeEffects[i];
        // 处理 HoT (Heal over Time)
        if (effect.type === 'hot' && effect.value > 0) {
            const healAmount = effect.value;
            character.hp = Math.min(character.maxHp, character.hp + healAmount);
            showHealAnimation(isPlayerSide ? playerSpriteElement : enemySpriteElement, healAmount);
            showStatusText(isPlayerSide ? playerSpriteElement : enemySpriteElement, 'heal', `+${healAmount} HoT`);
            gameState.log.push(`${character.name}持续恢复了${healAmount}点生命值！`);
            hasEffectLog = true;
            updateBattleUI(); // 更新UI以反映HoT效果
            await new Promise(resolve => setTimeout(resolve, 500));
        }
    }
    if (hasEffectLog) {
        updateBattleLog(); // 确保日志在HoT后更新
    }
}

// 新函数：处理回合结束时的效果 (持续时间减少和移除)
async function processEndOfTurnEffects(character, isPlayerSide) {
    const effectsToRemove = [];
    let hasEffectLog = false;

    for (let i = 0; i < character.activeEffects.length; i++) {
        const effect = character.activeEffects[i];
        if (effect.duration > 0) {
            effect.duration--; // 在回合结束时减少持续时间
            if (effect.duration === 0) {
                effectsToRemove.push(effect);
                hasEffectLog = true;
            }
        }
    }

    effectsToRemove.forEach(effect => removeEffect(character, effect));
    updateBattleUI(); // 更新UI以反映移除的效果和图标

    if (hasEffectLog) {
        await new Promise(resolve => setTimeout(resolve, 800)); // 短暂延迟以显示效果移除的日志
    }
}


// 使用技能（含回合保护与防抖）
async function useSkill(skillId) {
    // 确保在技能使用前，玩家输入未被锁定，且未被眩晕或沉默
    if (!gameState.isPlayerTurn || gameState.playerBlockedInput || gameState.player.isStunned || gameState.player.isSilenced) {
        console.warn("Player input blocked or character stunned/silenced.");
        return;
    }

    const skill = gameState.player.skills.find(s => s.id === skillId);
    // 这里不再检查 isSilenced，因为外层条件已经判断。canUseSkill 内部会专门判断技能是否可用
    if (!skill || !canUseSkill(gameState.player, skill)) {
        gameState.log.push(`${gameState.player.name}试图使用${skill.name}，但MP不足、PP耗尽或被沉默了！`);
        updateBattleUI();
        return; // 技能使用失败
    }

    gameState.playerBlockedInput = true; // 锁定玩家输入，直到回合结束

    // 扣资源
    gameState.player.mp -= skill.cost;
    skill.pp -= 1;
    skill.used = (skill.used || 0) + 1;

    gameState.log.push(`${gameState.player.name}使用了${skill.name}！`);
    updateBattleUI(); // 立即更新UI，显示MP/PP消耗和按钮禁用状态

    // 多段伤害处理
    const numHits = skill.numHits || 1;
    for (let i = 0; i < numHits; i++) {
        if (skill.damage > 0) {
            const { dmg, weakness, resistance } = calculateEffectiveDamage(skill.damage, gameState.player, gameState.enemy, skill.critical);
            gameState.enemy.hp = Math.max(0, gameState.enemy.hp - dmg);
            showDamageAnimation(enemySpriteElement, dmg);
            showStatusText(enemySpriteElement, 'hit', `-${dmg}`);
            gameState.log.push(`${gameState.enemy.name}受到了${dmg}点伤害！`);
            if (weakness) gameState.log.push(`(属性克制，伤害加成！)`);
            if (resistance) gameState.log.push(`(属性被克制，伤害减免！)`);
        }
        updateBattleUI(); // 每次伤害后更新UI和日志
        await new Promise(resolve => setTimeout(resolve, 300)); // 每段伤害间隔
        if (gameState.enemy.hp <= 0) break; // 敌人已死，停止连击
    }


    if (skill.damage < 0) {
        const heal = Math.abs(skill.damage);
        gameState.player.hp = Math.min(gameState.player.maxHp, gameState.player.hp + heal);
        showHealAnimation(playerSpriteElement, heal);
        showStatusText(playerSpriteElement, 'heal', `+${heal}`);
        gameState.log.push(`${gameState.player.name}恢复了${heal}点生命值！`);
        updateBattleUI(); // 治疗后更新UI和日志
        await new Promise(resolve => setTimeout(resolve, 800)); // 等待治疗动画
    }

    // 状态效果 (Buff/Debuff/Stun/Silence/HoT)
    if (skill.buff) {
        for (const type in skill.buff) {
            applyEffect(gameState.player, `buff_${type}`, skill.buff[type], skill.effectDuration, skill.name);
        }
    }
    if (skill.debuff) {
        for (const type in skill.debuff) {
            applyEffect(gameState.enemy, `debuff_${type}`, skill.debuff[type], skill.effectDuration, skill.name);
        }
    }
    // 状态效果（眩晕或沉默）现在需要概率判断
    if (skill.statusEffect) {
        const successChance = skill.chance !== undefined ? skill.chance : 1; // 默认100%几率
        if (Math.random() < successChance) {
            if (skill.statusEffect === 'stun') {
                applyEffect(gameState.enemy, 'stun', 0, skill.effectDuration, skill.name);
            } else if (skill.statusEffect === 'silence') {
                applyEffect(gameState.enemy, 'silence', 0, skill.effectDuration, skill.name);
            }
        } else {
            gameState.log.push(`${gameState.player.name}的${skill.name}未能对${gameState.enemy.name}生效。`);
        }
    }
    if (skill.hot) { // 持续治疗
        applyEffect(gameState.player, 'hot', skill.hot.value, skill.hot.duration, skill.name);
    }

    if (skill.restoreMp) {
        gameState.player.mp = Math.min(gameState.player.maxMp, gameState.player.mp + skill.restoreMp);
        showStatusText(playerSpriteElement, 'note', `+${skill.restoreMp} MP`);
    }
    if (skill.recoil) {
        gameState.player.hp = Math.max(0, gameState.player.hp - skill.recoil);
        showStatusText(playerSpriteElement, 'hit', `-${skill.recoil} 反冲`);
        gameState.log.push(`${gameState.player.name}受到了${skill.recoil}点反冲伤害！`);
        updateBattleUI(); // 反冲后更新UI和日志
        await new Promise(resolve => setTimeout(resolve, 800)); // 等待反冲伤害动画
    }

    updateBattleUI(); // 再次更新UI以显示最新状态


    // 检查战斗是否结束
    if (gameState.enemy.hp <= 0) {
        gameState.playerBlockedInput = false; // 战斗结束时解锁输入
        endBattle(true);
        return;
    }

    await processEndOfTurnEffects(gameState.player, true); // 处理玩家回合结束时的效果 (持续时间减少)

    // 切换回合到敌人
    gameState.isPlayerTurn = false;
    await applyStartOfTurnEffects(gameState.enemy, false); // 敌人回合开始时处理效果 (HoT/DoT)
    updateBattleUI(); // 更新UI以显示敌人回合状态
    setTimeout(() => enemyTurn(), 1500); // 增加1.5秒延迟给敌人“思考”
    // gameState.playerBlockedInput 会在敌方回合结束后被重置
}

// 敌人回合 (AI 优化)
async function enemyTurn() {
    if (gameState.isPlayerTurn || gameState.enemyBlockedInput) {
        console.warn("Enemy input blocked or it's player's turn.");
        return;
    }

    gameState.enemyBlockedInput = true; // 锁定敌人行动

    // 如果敌人被眩晕，则跳过回合
    if (gameState.enemy.isStunned) {
        gameState.log.push(`${gameState.enemy.name}因眩晕无法行动！`);
        updateBattleUI(); // 确保眩晕状态图标的视觉反馈也即时更新
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        await processEndOfTurnEffects(gameState.enemy, false); // 敌人眩晕回合结束，减少持续时间

        // 敌人回合跳过，切换到玩家回合
        gameState.isPlayerTurn = true;
        await applyStartOfTurnEffects(gameState.player, true); // 玩家回合开始时处理效果
        gameState.playerBlockedInput = false; // 解锁玩家输入
        updateBattleUI();
        gameState.enemyBlockedInput = false; // 解锁敌人行动
        setTimeout(() => playerTurn(), 500); // 启动玩家回合
        return;
    }

    // 获取敌人当前计算后的属性
    calculateCurrentStats(gameState.enemy);
    calculateCurrentStats(gameState.player); // 也需要最新的玩家状态

    const availableSkills = gameState.enemy.skills.filter(s => canUseSkill(gameState.enemy, s));
    let skillToUse = null;

    // --- AI 策略 ---
    // 1. 如果敌人HP低于30%，优先治疗自己
    if (gameState.enemy.hp / gameState.enemy.maxHp < 0.3) {
        skillToUse = availableSkills.find(s => s.damage < 0 || s.hot); // 寻找治疗或HoT技能
        if (skillToUse) {
            console.log("DEBUG(Enemy AI): Enemy is low HP, chose heal/hot skill:", skillToUse.name);
            gameState.log.push(`${gameState.enemy.name}生命垂危，优先使用了${skillToUse.name}！`);
        }
    }

    // 2. 如果玩家有强力Buff，优先解除/Debuff玩家
    if (!skillToUse && gameState.player.activeEffects.some(e => e.type.startsWith('buff_'))) {
        skillToUse = availableSkills.find(s => s.debuff || s.statusEffect === 'silence' || s.statusEffect === 'stun');
        if (skillToUse) {
            console.log("DEBUG(Enemy AI): Player has buff, chose debuff/control skill:", skillToUse.name);
            gameState.log.push(`${gameState.enemy.name}试图削弱${gameState.player.name}！`);
        }
    }

    // 3. 寻找对玩家属性克制的攻击技能
    if (!skillToUse) {
        const strongAttacks = availableSkills.filter(s =>
            s.damage > 0 && ELEMENT_CHART[gameState.enemy.element]?.strong.includes(gameState.player.element)
        );
        if (strongAttacks.length > 0) {
            // 修正：使用正确的 reduce 方式，确保返回有效技能对象
            skillToUse = strongAttacks.reduce((max, s) => {
                const currentTotalDmg = (s.damage || 0) * (s.numHits || 1);
                const maxTotalDmg = (max.damage || 0) * (max.numHits || 1);
                return currentTotalDmg > maxTotalDmg ? s : max;
            });
            console.log("DEBUG(Enemy AI): Found strong attack skill:", skillToUse.name);
            gameState.log.push(`${gameState.enemy.name}发现了属性克制，使用了${skillToUse.name}！`);
        }
    }

    // 4. 选择伤害最高的攻击技能
    if (!skillToUse) {
        const attackSkills = availableSkills.filter(s => s.damage > 0);
        if (attackSkills.length > 0) {
            // 选择伤害最高的攻击技能，考虑多段伤害
            skillToUse = attackSkills.reduce((max, s) => {
                const currentTotalDmg = (s.damage || 0) * (s.numHits || 1);
                const maxTotalDmg = (max.damage || 0) * (max.numHits || 1);
                return currentTotalDmg > maxTotalDmg ? s : max;
            });
            console.log("DEBUG(Enemy AI): Chose highest damage attack skill:", skillToUse.name);
            gameState.log.push(`${gameState.enemy.name}发动了强力攻击！`);
        }
    }

    // 5. 如果都没有，随便选一个技能
    if (!skillToUse && availableSkills.length > 0) {
        skillToUse = availableSkills[Math.floor(Math.random() * availableSkills.length)];
        console.log("DEBUG(Enemy AI): Chose random skill:", skillToUse.name);
        gameState.log.push(`${gameState.enemy.name}使用了${skillToUse.name}！`);
    }


    // --- 执行技能或普攻 ---
    if (skillToUse) {
        gameState.enemy.mp -= skillToUse.cost;
        skillToUse.pp -= 1;
        skillToUse.used = (skillToUse.used || 0) + 1;

        gameState.log.push(`${gameState.enemy.name}使用了${skillToUse.name}！`);
        updateBattleUI(); // 立即更新UI，显示MP/PP消耗和日志

        // 多段伤害处理
        const numHits = skillToUse.numHits || 1;
        for (let i = 0; i < numHits; i++) {
            if (skillToUse.damage > 0) {
                const { dmg, weakness, resistance } = calculateEffectiveDamage(skillToUse.damage, gameState.enemy, gameState.player, skillToUse.critical);
                gameState.player.hp = Math.max(0, gameState.player.hp - dmg);
                showDamageAnimation(playerSpriteElement, dmg);
                showStatusText(playerSpriteElement, 'hit', `-${dmg}`);
                gameState.log.push(`${gameState.player.name}受到了${dmg}点伤害！`);
                if (weakness) gameState.log.push(`(属性克制，伤害加成！)`);
                if (resistance) gameState.log.push(`(属性被克制，伤害减免！)`);
            }
            updateBattleUI(); // 每次伤害后更新UI和日志
            await new Promise(resolve => setTimeout(resolve, 300)); // 每段伤害间隔
            if (gameState.player.hp <= 0) break; // 玩家已死，停止连击
        }

        if (skillToUse.damage < 0) {
            const heal = Math.abs(skillToUse.damage);
            gameState.enemy.hp = Math.min(gameState.enemy.maxHp, gameState.enemy.hp + heal);
            showHealAnimation(enemySpriteElement, heal);
            showStatusText(enemySpriteElement, 'heal', `+${heal}`);
            gameState.log.push(`${gameState.enemy.name}恢复了${heal}点生命值！`);
            updateBattleUI(); // 治疗后更新UI和日志
            await new Promise(resolve => setTimeout(resolve, 800)); // 等待治疗动画
        }

        // 状态效果 (Buff/Debuff/Stun/Silence/HoT)
        if (skillToUse.buff) {
            for (const type in skillToUse.buff) {
                applyEffect(gameState.enemy, `buff_${type}`, skillToUse.buff[type], skillToUse.effectDuration, skillToUse.name);
            }
        }
        if (skillToUse.debuff) {
            for (const type in skillToUse.debuff) {
                applyEffect(gameState.player, `debuff_${type}`, skillToUse.debuff[type], skillToUse.effectDuration, skillToUse.name);
            }
        }
        // 状态效果（眩晕或沉默）现在需要概率判断
        if (skillToUse.statusEffect) {
            const successChance = skillToUse.chance !== undefined ? skillToUse.chance : 1; // 默认100%几率
            if (Math.random() < successChance) {
                if (skillToUse.statusEffect === 'stun') {
                    applyEffect(gameState.player, 'stun', 0, skillToUse.effectDuration, skillToUse.name);
                } else if (skillToUse.statusEffect === 'silence') {
                    applyEffect(gameState.player, 'silence', 0, skillToUse.effectDuration, skillToUse.name);
                }
            } else {
                gameState.log.push(`${gameState.enemy.name}的${skillToUse.name}未能对${gameState.player.name}生效。`);
            }
        }
        if (skillToUse.hot) { // 持续治疗
            applyEffect(gameState.enemy, 'hot', skillToUse.hot.value, skillToUse.hot.duration, skillToUse.name);
        }

        if (skillToUse.restoreMp) {
            gameState.enemy.mp = Math.min(gameState.enemy.maxMp, gameState.enemy.mp + skillToUse.restoreMp);
            showStatusText(enemySpriteElement, 'note', `+${skillToUse.restoreMp} MP`);
        }
        if (skillToUse.recoil) {
            gameState.enemy.hp = Math.max(0, gameState.enemy.hp - skillToUse.recoil);
            showStatusText(enemySpriteElement, 'hit', `-${skillToUse.recoil} 反冲`);
            gameState.log.push(`${gameState.enemy.name}受到了${skillToUse.recoil}点反冲伤害！`);
            updateBattleUI(); // 反冲后更新UI和日志
            await new Promise(resolve => setTimeout(resolve, 800)); // 等待反冲伤害动画
        }
    } else {
        // 没有可用技能，执行普通攻击
        console.log("DEBUG(Enemy AI): No skill chosen, performing basic attack.");
        gameState.log.push(`${gameState.enemy.name}别无选择，发动了普通攻击！`);
        const ended = await performBasicAttack(gameState.enemy, gameState.player, false);
        if (ended) { 
            gameState.enemyBlockedInput = false; // 战斗结束时解锁
            gameState.playerBlockedInput = false;
            return; 
        }
        updateBattleUI(); // 普攻后更新UI和日志
    }

    updateBattleUI(); // 再次更新UI以显示最新状态

    if (gameState.player.hp <= 0) {
        gameState.enemyBlockedInput = false; // 战斗结束时解锁
        gameState.playerBlockedInput = false;
        endBattle(false);
        return;
    }

    await processEndOfTurnEffects(gameState.enemy, false); // 处理敌人回合结束时的效果 (持续时间减少)

    // 敌人回合结束，切换到玩家回合
    gameState.isPlayerTurn = true;
    await applyStartOfTurnEffects(gameState.player, true); // 玩家回合开始时处理效果
    gameState.playerBlockedInput = false; // 解锁玩家输入
    updateBattleUI();
    gameState.enemyBlockedInput = false; // 解锁敌人行动
    setTimeout(() => playerTurn(), 500); // 启动玩家回合
}

// 新函数：玩家回合处理
async function playerTurn() {
    gameState.playerBlockedInput = true; // 初始锁定输入，直到回合开始效果处理完毕

    // 确保玩家属性在处理回合开始效果前是最新的
    calculateCurrentStats(gameState.player);
    
    await applyStartOfTurnEffects(gameState.player, true); // 应用玩家回合开始时效果 (HoT/DoT)
    updateBattleUI(); // 更新UI以反映效果

    // 如果玩家被眩晕，则跳过回合
    if (gameState.player.isStunned) {
        gameState.log.push(`${gameState.player.name}因眩晕无法行动！`);
        updateBattleUI();
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        await processEndOfTurnEffects(gameState.player, true); // 玩家眩晕回合结束，减少持续时间
        
        // 玩家回合跳过，切换到敌人回合
        gameState.isPlayerTurn = false;
        await applyStartOfTurnEffects(gameState.enemy, false); // 敌人回合开始时处理效果
        gameState.playerBlockedInput = false; // 玩家输入锁定直到下一个玩家回合
        updateBattleUI();
        setTimeout(() => enemyTurn(), 1500); // 启动敌人回合
        return;
    }

    // 如果玩家未被眩晕，则解锁输入并等待玩家行动
    gameState.playerBlockedInput = false; // 解锁输入，玩家现在可以操作
    updateBattleUI(); // 再次更新UI以确保按钮状态正确显示
}


// 计算有效伤害（属性克制 + 攻防修正 + 暴击）
function calculateEffectiveDamage(baseDamage, attacker, defender, isCritical = false) {
    let mult = 1;
    let weakness = false;
    let resistance = false;

    // 属性克制
    const attackerElementChart = ELEMENT_CHART[attacker.element] || ELEMENT_CHART.neutral;
    if (attackerElementChart.strong.includes(defender.element)) {
        mult = 1.5;
        weakness = true;
    } else if (attackerElementChart.weak.includes(defender.element)) {
        mult = 0.5;
        resistance = true;
    }

    // 攻防计算
    // attacker.currentAttack 和 defender.currentDefense 已经包含了所有 buff/debuff 效果
    const attackValue = attacker.currentAttack;
    const defenseValue = defender.currentDefense;

    // 简单地将攻击力加到基础伤害上，然后减去防御力
    let rawDamage = baseDamage + attackValue - defenseValue;
    rawDamage = Math.max(1, rawDamage); // 确保伤害至少为1

    // 暴击处理 (如果技能设定为必定暴击)
    if (isCritical) {
        mult *= 1.5; // 暴击伤害倍数
        gameState.log.push(`${attacker.name}的攻击暴击了！`);
        showStatusText(attacker === gameState.player ? enemySpriteElement : playerSpriteElement, 'hit', `暴击！`);
    }

    let finalDmg = Math.round(rawDamage * mult);

    return { dmg: finalDmg, weakness, resistance };
}


// 动画（贴头像）
function showDamageAnimation(targetElement, damage) {
    if (!targetElement) return;
    targetElement.classList.add('animate-shake');
    setTimeout(() => targetElement.classList.remove('animate-shake'), 400);

    const el = document.createElement('div');
    el.className = 'status-fx hit'; // 使用 status-fx 类，并指定类型
    el.textContent = `-${damage}`;
    targetElement.parentNode.appendChild(el);
    setTimeout(() => el.remove(), 900);
}

function showHealAnimation(targetElement, healAmount) {
    if (!targetElement) return;
    const el = document.createElement('div');
    el.className = 'status-fx heal'; // 使用 status-fx 类
    el.textContent = `+${healAmount}`;
    targetElement.parentNode.appendChild(el);
    setTimeout(() => el.remove(), 900);
}

// 结束战斗
function endBattle(playerWon) {
    const resultTitle = document.getElementById('result-title');
    const resultMessage = document.getElementById('result-message');
    gameState.playerBlockedInput = true; // 战斗结束，锁定输入

    if (playerWon) {
        resultTitle.textContent = '战斗胜利！';
        resultMessage.textContent = `你成功击败了${gameState.enemy.name}！`;

        if (gameState.currentBattle >= gameState.totalBattles) {
            resultTitle.textContent = '恭喜你！';
            resultMessage.textContent = '你已经击败了所有对手，完成了挑战！';
            nextLevelButton.textContent = '再来一次'; // 最终胜利后“下一关”变成“再来一次”
        } else {
            nextLevelButton.textContent = '下一关';
        }
        nextLevelButton.classList.remove('hidden');
    } else {
        resultTitle.textContent = '战斗失败';
        resultMessage.textContent = `你被${gameState.enemy.name}击败了，请再接再厉！`;
        nextLevelButton.classList.add('hidden'); // 失败不显示下一关
    }

    resultModal.classList.remove('hidden');
}

// 下一场战斗
function startNextBattle() {
    resultModal.classList.add('hidden');
    // gameState.playerBlockedInput = false; // 将在 playerTurn 中设置

    if (gameState.currentBattle >= gameState.totalBattles) {
        restartGame(); // 如果已经通过所有关卡，则重启游戏
        return;
    }
    gameState.currentBattle++;

    // 重置玩家状态，轻微恢复，并清除所有状态效果
    if (gameState.player) {
        // --- 玩家永久成长 ---
        gameState.player.baseHp += 5; // 每关增加5点基础HP
        gameState.player.baseMp += 3; // 每关增加3点基础MP
        gameState.player.baseAttack += 1; // 每关增加1点基础攻击
        gameState.player.baseDefense += 1; // 每关增加1点基础防御
        gameState.player.baseSpeed += 1; // 每关增加1点基础速度

        // 根据新的基础属性更新最大值
        gameState.player.maxHp = gameState.player.baseHp;
        gameState.player.maxMp = gameState.player.baseMp;

        // --- 恢复当前HP/MP（基于新的最大值）---
        gameState.player.hp = Math.min(gameState.player.maxHp, Math.round(gameState.player.maxHp * 0.7)); // 恢复到70%血量
        gameState.player.mp = Math.min(gameState.player.maxMp, Math.round(gameState.player.maxMp * 0.8)); // 恢复到80%蓝量
        
        gameState.player.activeEffects = []; // 清除所有状态效果
        gameState.player.skills.forEach(s => {
            s.pp = s.originalPP; // 恢复PP
            s.used = 0;
        });
    }

    // 筛选可用敌人：排除玩家自己，以及上一关的敌人
    let validEnemies = characters.filter(c =>
        c.id !== gameState.player.id && c.id !== (gameState.enemy ? gameState.enemy.id : -1)
    );
    if (validEnemies.length === 0) { // 如果只剩一个敌人或所有敌人都打过了，重新选择除了玩家自己以外的所有敌人
        validEnemies = characters.filter(c => c.id !== gameState.player.id);
    }

    gameState.enemy = JSON.parse(JSON.stringify(validEnemies[Math.floor(Math.random() * validEnemies.length)]));
    gameState.enemy.maxHp = gameState.enemy.baseHp;
    gameState.enemy.maxMp = gameState.enemy.baseMp;
    gameState.enemy.hp = gameState.enemy.maxHp;
    gameState.enemy.mp = gameState.enemy.maxMp;
    gameState.enemy.activeEffects = []; // 清除所有状态效果
    gameState.enemy.skills.forEach(s => {
        s.pp = s.originalPP;
        s.used = 0;
    });

    // 敌人难度根据关卡提升
    const difficultyMultiplier = 1 + (gameState.currentBattle * 0.15); // 每关敌人属性增加15%
    gameState.enemy.maxHp = Math.round(gameState.enemy.maxHp * difficultyMultiplier);
    gameState.enemy.hp = gameState.enemy.maxHp; // 敌人满血
    gameState.enemy.maxMp = Math.round(gameState.enemy.maxMp * (1 + (gameState.currentBattle * 0.1))); // MP增加10%
    gameState.enemy.mp = gameState.enemy.maxMp;
    gameState.enemy.baseAttack = Math.round(gameState.enemy.baseAttack * (1 + (gameState.currentBattle * 0.08))); // 攻击增加8%
    gameState.enemy.baseDefense = Math.round(gameState.enemy.baseDefense * (1 + (gameState.currentBattle * 0.08))); // 防御增加8%

    gameState.isPlayerTurn = true;
    gameState.playerBlockedInput = false;
    gameState.enemyBlockedInput = false;
    gameState.log = [`战斗 ${gameState.currentBattle}/${gameState.totalBattles} 开始！对手是${gameState.enemy.name}！`];

    // 重新计算双方属性
    calculateCurrentStats(gameState.player);
    calculateCurrentStats(gameState.enemy);

    updateBattleUI();
    setTimeout(() => playerTurn(), 500); // 启动玩家的回合逻辑
}

// 重新开始
function restartGame() {
    resultModal.classList.add('hidden');
    pauseMenu.classList.add('hidden');
    battleScreen.classList.add('hidden');
    characterSelection.classList.remove('hidden');

    gameState.player = null;
    gameState.enemy = null;
    gameState.currentBattle = 1;
    gameState.isPlayerTurn = true;
    gameState.playerBlockedInput = false; // 确保重新开始时玩家输入是解锁的
    gameState.enemyBlockedInput = false;
    gameState.log = [];

    // 清除眩晕特效
    playerStunOverlay.classList.remove('active');
    enemyStunOverlay.classList.remove('active');
}

// 返回角色选择
function returnToCharacterSelection() {
    pauseMenu.classList.add('hidden');
    battleScreen.classList.add('hidden');
    characterSelection.classList.remove('hidden');
    restartGame(); // 清空状态，回到角色选择
}

// 界面导航
function goToCharacterSelection() {
    startScreen.classList.add('hidden');
    characterSelection.classList.remove('hidden');
}
function goToStartScreen() {
    characterSelection.classList.add('hidden');
    startScreen.classList.remove('hidden');
}
function goToBattleScreen() {
    characterSelection.classList.add('hidden');
    battleScreen.classList.remove('hidden');
    gameState.log = [`战斗 ${gameState.currentBattle}/${gameState.totalBattles} 开始！对手是${gameState.enemy.name}！`];
    updateBattleUI();
    // 战斗开始，启动玩家的第一个回合
    setTimeout(() => playerTurn(), 500);
}

// 暂停
function showPauseMenu() { pauseMenu.classList.remove('hidden'); }
function hidePauseMenu() { pauseMenu.classList.add('hidden'); }

// 启动
window.addEventListener('DOMContentLoaded', initGame);
